import axios from 'axios'

let fileName = ''
export function downloadFile(api, params, fileName, type = 'GET') {
    // 方式1--axios下载文件
    axios({
        method: type,
        url: '' + api,
        responseType: 'blob',
        params: params,
        headers: {
            // [AUTH]: storage('tokenHead') + storage(`token-${SOURCE_TYPE}`),
            // [OPERATING_SYSTEM_KEY]: [OPERATING_SYSTEM_VALUE]
        }
    }).then((res) => {
        let str = res.headers['content-disposition']
        if (!res || !str) {
            ElMessage({
                type: 'error',
                message: '合同不存在',
                duration: 5 * 1000,
                showClose: true,
            })
            return;
        }
        ElMessage({
            type: 'success',
            message: '合同下载中...',
            duration: 5 * 1000,
            showClose: true,
        })
        let suffix = ''
        // 截取文件名和文件类型
        if (str.lastIndexOf('.')) {
            fileName ? '' : fileName = decodeURI(str.substring(str.indexOf('=') + 1, str.lastIndexOf('.')))
            suffix = str.substring(str.lastIndexOf('.'), str.length)
        }
        //  如果支持微软的文件下载方式(ie10+浏览器)
        if (window.navigator.msSaveBlob) {
            try {
                const blobObject = new Blob([res.data]);
                window.navigator.msSaveBlob(blobObject, fileName + suffix);
            } catch (e) {
                console.log(e);
            }
        } else {
            //  其他浏览器
            let url = window.URL.createObjectURL(res.data)
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', fileName + suffix)
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
            window.URL.revokeObjectURL(link.href);
        }
    }).catch((err) => {
        console.log(err.message);
    })


}
